package rpc

import (
	"go-ddd/config"
	"go-ddd/internal/common/logs"
	"go-ddd/internal/servers"
	"go.uber.org/zap"
	"google.golang.org/grpc"
	"net"
)

var _ servers.ServerInterface = &RpcServer{}

type RpcServer struct {
	srv  *grpc.Server
	port string
	Apps *servers.Apps
}

func (r *RpcServer) AsyncStart() {
	logs.Infof("[服务启动][RPC] 服务地址: %s", r.port)
	go func() {
		l, err := net.Listen("tcp", ":"+r.port)
		if err != nil {
			logs.Fatalf("[RPC]服务启动该异常: %s", zap.Error(err))
			if err := r.srv.Serve(l); err != nil {
				logs.Fatalf("[RPC]服务启动该异常: %s", zap.Error(err))
			}
		}
	}()
}

func (r *RpcServer) Stop() {
	logs.Infof("[RPC]服务关闭")
	r.srv.GracefulStop()
}

func NewRpcServer(cfg *config.ConvertConfig, apps *servers.Apps) servers.ServerInterface {
	s := &RpcServer{
		port: cfg.RPC.Port,
		Apps: apps,
	}
	s.srv = grpc.NewServer()
	return s
}
